from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource,marshal,reqparse
from common.uitils.login_utils import login_required
from models.users import *
from models import db
import json
from common.model_fields.comment_fields import comments_fields

comment_bp = Blueprint('comment', __name__, url_prefix='/comments')
api = Api(comment_bp)


class CommenetResource(Resource):
    @login_required
    def get(self, nid):
        """
        获取所有的评论
        1.接受前端传来的文章id
        2.获取这个文章的所有评论
            1. 判断评论有没有被回复
            2. 若有回复，获取回复的评论内容
        3.返回的数据格式
        {
            "nid":nid,
            "comments":[
                'cid':1,
                ;content: '我冲着图片来的'
:            ]
        }
        """
        comment = Comment.query.filter_by(article_id=nid).all()
        if not comment:
            return jsonify(message="获取评论成功！", code=200, data=[])

        # 有评论   有序字典转换字典
        comment_dict = json.loads(json.dumps(marshal(comment, comments_fields)))

        for comment in comment_dict:
            # 获取用户信息
            user = UserModel.query.filter_by(uid=comment.get("user_id")).first()
            comment["user_info"] = {
                "uid": user.uid,
                "uname": user.uname,
                "profile_photo": user.profile_photo,
                "created_time": user.created_time,
            }

            parent_id = comment.get("cmid")
            comment_child = Comment.query.filter_by(parent_id=parent_id).all()
            comment_dict_child = json.loads(json.dumps(marshal(comment_child, comments_fields)))
            for comment_b in comment_dict_child:
                user_a = UserModel.query.filter_by(uid=comment_b.get("user_id")).first()
                comment_b["user_info"] = {
                    "uid": user_a.uid,
                    "uname": user_a.uname,
                    "profile_photo": user_a.profile_photo,
                }
            comment["child_comment"] = comment_dict_child
        # comments = Comment.query.filter_by(article_id=nid).all()
        # if not comments:
        #     # 说明文章没有评论
        #     return jsonify(message='获取评论成功', data=[], code=200)
        # # 有评论，把有序字段转化成字典
        # comments_dict = json.loads(json.dumps(marshal(comments, comments_fields)))
        # print('评论的字典数据>>>', comments_dict)
        # for comment in comments_dict:
        #     # 获取评论的用户id,获取用户信息
        #     user = UserModel.query.filter_by(uid=comment['user_id']).first()
        #     comment['user_info'] = {
        #         'uid':user.uid,
        #         'uname':user.uname,
        #         'profile_photo':user.profile_photo
        #     }
        #     # 判断文章是否有回复
        #     is_reply_comment = comment['parent_id']
        #     # 回复评论的数据
        #     child_comment = []
        #     if is_reply_comment:
        #         # 有回复
        #         # TODO 获取回复的评论内容及用户信息
        #         comments = Comment.query.filter_by(cmid=comment['parent_id']).all()
        #         comments_dict = json.loads(json.dumps(marshal(comments, comments_fields)))
        #         for comment in comments_dict:
        #             # 获取评论的用户id，获取用户信息
        #             user = UserModel.query.filter_by(uid=comment['user_id']).first()
        #             comment['user_info'] = {
        #                 'uid': user.uid,
        #                 'uname': user.uname,
        #                 'profile_photo': user.profile_photo
        #             }
        #     else:
        #         # 没有回复
        #         comment['child_comment'] = child_comment
            # 返回包含评论的说有数据
            print("评论内容>>>", comment_dict)
        return jsonify(message="获取评论成功", code=200,data=comment_dict)

    def post(self,nid):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('content')
            parser.add_argument('parent_id')
            parser.add_argument('article_id')
            args = parser.parse_args()

            content = args.get('content')
            parent_id = args.get('parent_id')
            article_id = args.get('article_id')
            if parent_id:
                comment = Comment(user_id=nid, parent_id=parent_id, content=content)
            else:
                comment = Comment(user_id=nid, article_id=article_id, content=content)
            db.session.add(comment)
            db.session.commit()
            return jsonify(message='发布成功', code=200)
        except Exception as e:
            print("发布评论的错误>>", e)
            return jsonify(message='服务器错误', code=500)


api.add_resource(CommenetResource, '/all/<int:nid>')